﻿/*
	Copyright (c) 2013 Andrew Meyer

	Permission is hereby granted, free of charge, to any person obtaining a copy of this software
	and associated documentation files (the "Software"), to deal in the Software without
	restriction, including without limitation the right to use, copy, modify, merge, publish,
	distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
	Software is furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all copies or
	substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
	BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
	DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using Ascend;

namespace AscendViewer
{
	public class MainWindowViewModel : ObservableObject
	{
		#region Lifecycle
		public MainWindowViewModel(Window window)
		{
			_window = window;

			// Create layered scenes with shared camera
			MainScene = new Scene3D();

			BoneScene = new Scene3D
			{
				Camera = MainScene.Camera
			};

			AxisScene = new Scene3D
			{
				Camera = MainScene.Camera
			};

			SetupLights();

			// Setup commands
			OpenFileCommand = new InterfaceCommand(OpenFileAction);
			ResetCameraCommand = new InterfaceCommand(AlignCamera, () => _loadedSceneNode != null);
			OpenHelpCommand = new InterfaceCommand(OpenHelpAction);

			ContentExplorer = new ContentExplorerViewModel(this);
		}
		#endregion

		#region Private Members
		private Window _window;
		private SceneNode _directionalLights;
		private LightSceneNode _ambientLight;
		private SceneNode _loadedSceneNode;
		private SceneNode _axisSceneAlias;
		private SceneNode _boneSceneAlias;
		private Queue<TransformableObject> _axisSceneAliases;
		private Queue<TransformableObject> _boneSceneAliases;
		#endregion

		#region Public Properties
		public ICommand OpenFileCommand
		{
			get;
			private set;
		}

		public ICommand ResetCameraCommand
		{
			get;
			private set;
		}

		public ICommand OpenHelpCommand
		{
			get;
			private set;
		}

		public Scene3D MainScene
		{
			get;
			private set;
		}

		public Scene3D BoneScene
		{
			get;
			private set;
		}

		public Scene3D AxisScene
		{
			get;
			private set;
		}

		public ContentExplorerViewModel ContentExplorer
		{
			get;
			private set;
		}

		private bool _showLights = true;
		public bool ShowLights
		{
			get
			{
				return _showLights;
			}

			set
			{
				if (_showLights == value)
				{
					return;
				}

				_showLights = value;

				if (_showLights)
				{
					_ambientLight.Parent = null;
					_directionalLights.Parent = MainScene.RenderRoot;
				}
				else
				{
					_directionalLights.Parent = null;
					_ambientLight.Parent = MainScene.RenderRoot;
				}

				NotifyPropertyChanged("ShowLights");
			}
		}

		private bool _showAxes;
		public bool ShowAxes
		{
			get
			{
				return _showAxes;
			}

			set
			{
				if (_showAxes == value)
				{
					return;
				}

				_showAxes = value;

				if (_showAxes)
				{
                    _axisSceneAlias.Parent = AxisScene.RenderRoot;
				}
				else
				{
                    _axisSceneAlias.Parent = null;
				}

				NotifyPropertyChanged("ShowAxes");
			}
		}

		private bool _canShowAxes = false;
		public bool CanShowAxes
		{
			get
			{
				return _canShowAxes;
			}

			set
			{
				if (_canShowAxes == value)
				{
					return;
				}

				_canShowAxes = value;

                // Turn off axes if false
                if (!_canShowAxes)
                {
                    ShowAxes = false;
                }

				NotifyPropertyChanged("CanShowAxes");
			}
		}
		#endregion

		#region Public Methods
		public void OpenFile(string filePath)
		{
			if (_loadedSceneNode != null)
			{
				ClearLastLoad();
			}

			try
			{
				// Load scene node
				_loadedSceneNode = Loader.Load<ModelSceneNode>(filePath);
                _loadedSceneNode.Parent = MainScene.RenderRoot;
				AlignCamera();

				// Get aliases for other scene layers
				_axisSceneAliases = GetAliases(_loadedSceneNode);
				_axisSceneAlias = (SceneNode)_axisSceneAliases.First();

				_boneSceneAliases = GetAliases(_loadedSceneNode);
				_boneSceneAlias = (SceneNode)_boneSceneAliases.First();
                _boneSceneAlias.Parent = BoneScene.RenderRoot;

				// Setup content explorer
				ContentExplorer.RootNode = ContentNodeViewModel.Create(_loadedSceneNode,
					_axisSceneAliases, _boneSceneAliases, ContentExplorer, null);
				ContentExplorer.SelectedContentNode = ContentExplorer.RootNode;
				ContentExplorer.IsExpanded = true;
				ContentExplorer.FileName = Path.GetFileName(filePath);

				// Allow axes, now that scenes are set up
				CanShowAxes = true;
			}
			catch (LoaderCompatibilityException ex)
			{
				System.Windows.MessageBox.Show(ex.Message, "Incompatible file", MessageBoxButton.OK,
					MessageBoxImage.Warning);
			}
			catch (ModelLoadException)
			{
				System.Windows.MessageBox.Show("Unable to open file \'" +
					Path.GetFileName(filePath) + "\'. The file may be corrupted.",
					"Unable to open file", MessageBoxButton.OK, MessageBoxImage.Warning);
			}
		}
		#endregion

		#region Private Methods
		private void SetupLights()
		{			
			// Create directional lights
			_directionalLights = ModelSceneNode.Create();
			Color color = Color.FromRgb(175, 175, 175);

			_directionalLights.Children.Add(
				LightSceneNode.Create(new DirectionalLight(color, new Vector3D(-2, -1, -2))));
			_directionalLights.Children.Add(
				LightSceneNode.Create(new DirectionalLight(color, new Vector3D(2, -1, -2))));
			_directionalLights.Children.Add(
				LightSceneNode.Create(new DirectionalLight(color, new Vector3D(0, 0, 1))));

			// Create ambient light
			_ambientLight = LightSceneNode.Create(new AmbientLight(Colors.White));

			// Add directional lights to main scene and bone scene
			MainScene.RenderRoot.Children.Add(_directionalLights);
			BoneScene.RenderRoot.Children.Add((SceneNode)_directionalLights.Clone());

			// Add ambient light to axis scene
			AxisScene.RenderRoot.Children.Add((SceneNode)_ambientLight.Clone());
		}

		private void ClearLastLoad()
		{
			// Remove node
			_loadedSceneNode.Parent = null;
			_loadedSceneNode = null;

			// Remove axes
			CanShowAxes = false;

			// Remove bones
			_boneSceneAlias.Parent = null;

			// Clear content explorer
			ContentExplorer.RootNode = null;
			ContentExplorer.FileName = string.Empty;
		}

		private void AlignCamera()
		{
			double fov = ((PerspectiveCamera)MainScene.Camera).FieldOfView;
			Rect3D bounds = MainScene.RenderRoot.Bounds;
			double xOrigin = bounds.X + bounds.SizeX / 2;
			double yOrigin = bounds.Y + bounds.SizeY / 2;
			double zOrigin = bounds.Z + bounds.SizeZ / 2;

			// Find which dimension to fit in view and pad it
			double dimToFit = Math.Max(bounds.SizeX, bounds.SizeY) * 2.0;

			// Compute distance based on field of view
			double distance = (dimToFit / 2) * Math.Tan((fov / 2) * (180 / Math.PI));

			// Align camera
			MainScene.Camera.Position = new Point3D(xOrigin, yOrigin, zOrigin + distance);
			MainScene.LookAt(new Point3D(xOrigin, yOrigin, zOrigin));
		}

		private Queue<TransformableObject> GetAliases(SceneNode node)
		{
			TransformableObject alias = node.Clone();
			List<TransformableObject> aliases = alias.GetDescendants().ToList();
			aliases.Insert(0, alias);

			return new Queue<TransformableObject>(aliases);
		}

		private void OpenFileAction()
		{
			OpenFileDialog dlg = new OpenFileDialog();
			dlg.Filter = "Ascend (*.asc)|*.asc";
			dlg.RestoreDirectory = true;

			if (dlg.ShowDialog() == DialogResult.OK)
			{
				OpenFile(dlg.FileName);
			}
		}

		private void OpenHelpAction()
		{
			HelpWindow wnd = new HelpWindow();
			wnd.Owner = _window;

			wnd.Show();
		}
		#endregion
	}
}
